package cn.tedu.straw.portal.service.impl;

import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.ex.StrawException;
import cn.tedu.straw.portal.mapper.AnswerMapper;
import cn.tedu.straw.portal.mapper.QuestionMapper;
import cn.tedu.straw.portal.model.Answer;
import cn.tedu.straw.portal.model.Question;
import cn.tedu.straw.portal.result.ResultCodeEnum;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.vo.AnswerListItemVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-11
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements IAnswerService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private AnswerMapper answerMapper;

    @Override
    public void post(PostAnswerDTO postAnswerDTO, Integer userId, String userNickName) {

        //写答案之前先查一下问题是否存在
        Question question = questionMapper.selectById(postAnswerDTO.getQuestionId());
        if (question == null){
            throw new StrawException(ResultCodeEnum.QUESTION_NOT_FOUND_ANSWER_ERROR);
        }
        //创建答案实体类
        Answer answer = new Answer();
        //创建时间对象
        LocalDateTime now = LocalDateTime.now();
        //设置答案正文
        answer.setContent(postAnswerDTO.getContent());
        //答案作者ID
        answer.setUserId(userId);
        //答案作者昵称
        answer.setUserNickName(userNickName);
        //问题ID
        answer.setQuestionId(postAnswerDTO.getQuestionId());
        //是否采纳
        answer.setIsAccepted(0);
        //答案发布日期
        answer.setGmtCreate(now);
        //更新日期
        answer.setGmtModified(now);

        int rows = answerMapper.insert(answer);
        if (rows != 1){
            throw new StrawException(ResultCodeEnum.INSERT_ERROR);
        }
    }

    @Override
    public List<AnswerListItemVO> getAnswerList(Integer questionId) {
        return answerMapper.findByQuestionId(questionId);
    }
}
